"""
KPL股票数据服务
处理KPL股票数据的业务逻辑
"""
import requests
from typing import List, Dict, Any
from datetime import datetime
from app.core.config import Settings

settings = Settings()


class KPLStockService:
    """KPL股票数据服务类"""
    
    @staticmethod
    async def fetch_kpl_stocks_from_api(date: str = None, page: int = 1, page_size: int = 50) -> List[Dict[str, Any]]:
        """
        从开盘啦接口获取实时龙虎榜数据
        
        Args:
            date: 日期，格式为YYYY-MM-DD，默认为今天
            page: 页码，默认为1
            page_size: 每页数据量，默认为50
            
        Returns:
            股票数据列表
        """
        if not date:
            date = datetime.now().strftime("%Y-%m-%d")
            
        # 计算index参数，用于分页
        index = page_size * (page - 1)
            
        # 根据HTML示例中的参数构造请求URL
        base_url = "https://apphis.longhuvip.com/w1/api/index.php"
        params = {
            "Order": "1",
            "a": "HisRankingInfo_W8",
            "st": str(page_size),
            "c": "HisStockRanking",
            "PhoneOSNew": "1",
            "RStart": "0925",
            "Isst": "1",
            "index": str(index),
            "REnd": "1500",
            "apiv": "w33",
            "Type": "9",
            "Date": date
        }
        
        try:
            response = requests.get(base_url, params=params, timeout=10)
            response.raise_for_status()
            data = response.json()
            # 返回原始列表数据
            return data.get("list", [])
        except Exception as e:
            print(f"获取开盘啦数据失败: {e}")
            return []